package com.hs.core.utils;
import java.io.File;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream; //这个包在ant.jar里，要到官方网下载

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;

public class ZipfileUtil {
	public ZipfileUtil() {}

    /**//*
    * inputFileName 输入一个文件夹
    * zipFileName 输出一个压缩文件夹
    */
    public void zip(String zipFileName,String inputFileName) throws Exception {
        System.out.println(zipFileName);
        zip(zipFileName, new File(inputFileName));
    }

    private void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, "");
        System.out.println("zip done");
        out.close();
    }

    private void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
           File[] fl = f.listFiles();
           out.setEncoding("gbk");   
           out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
           base = base.length() == 0 ? "" : base + "/";
           for (int i = 0; i < fl.length; i++) {
        	   System.out.println("fl[i].getName():::" + fl[i].getName());
           zip(out, fl[i], base + fl[i].getName());
         }
        }else {
           out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
           FileInputStream in = new FileInputStream(f);
           int b;
           System.out.println(base);
           while ( (b = in.read()) != -1) {
            out.write(b);
         }
         in.close();
       }
    }
    
    public void unzip(String fileName,String outputfilepath) throws Exception{
		 ZipFile zipFile = new ZipFile(fileName,"GBK"); //以“GBK”编码创建zip文件，用来处理winRAR压缩的文件。
		   Enumeration emu = zipFile.getEntries();
		  
		  
		   while(emu.hasMoreElements()){
		    ZipEntry entry = (ZipEntry) emu.nextElement();
		    if (entry.isDirectory()){
		     new File(outputfilepath+entry.getName()).mkdirs();
		     continue;
		    }
		    BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
		   
		    File file = new File(outputfilepath + entry.getName());
		    File parent = file.getParentFile();
		    if(parent != null && (!parent.exists())){
		     parent.mkdirs();
		    }
		    FileOutputStream fos = new FileOutputStream(file);
		    BufferedOutputStream bos = new BufferedOutputStream(fos,1024);

		    byte [] buf = new byte[1024];
		    int len = 0;
		    while((len=bis.read(buf,0,1024))!=-1){
		     fos.write(buf,0,len);
		    }
		    bos.flush();
		    bos.close();
		    bis.close();
		    System.out.println("解压文件："+file.getName());
		   }
		   zipFile.close();


	 }

}
